﻿using UnityEngine.UI;
using UnityEngine;
using DG.Tweening;

public class TankHealth : MonoBehaviour {

    public float startHealth = 100f;
    public Slider slider;
    public Image fillImage;
    public Color fullHealthColor = Color.green;
    public Color midHealthColor = Color.yellow;
    public Color zeroHealthColor = Color.red;
    public GameObject explosionPrefab;
    public GameObject ruins;

    private ParticleSystem _explosion;
    private float _curHealth;
    [HideInInspector]
    public bool isDead;

	void Awake()
    {
        
    }
	
	void OnEnable()
    {
        _curHealth = startHealth;
        isDead = false;
        UpdateHealthUI();
    }

    public void TakeDamage(float amount)
    {
        _curHealth -= amount;
        UpdateHealthUI();
        if(_curHealth <= 0f && !isDead)
        {
            SetToDeath();
        }
    }

    private void UpdateHealthUI()
    {
        if(slider)
        {
            //slider.value = _curHealth;
            slider.DOValue(_curHealth, .5f).SetEase(Ease.OutQuint);
            if (_curHealth / startHealth > 0.5f)
            {
                fillImage.color = Color.Lerp(midHealthColor, fullHealthColor, _curHealth / startHealth);
            }
            else
            {
                fillImage.color = Color.Lerp(zeroHealthColor, midHealthColor, _curHealth / startHealth);
            }
        }
    }

    private void SetToDeath()
    {
        isDead = true;
        if(_explosion==null)
        {
            _explosion = Instantiate(explosionPrefab).GetComponent<ParticleSystem>();

        }
        _explosion.transform.position = transform.position;
        _explosion.Play();

        if(ruins!=null)
        {
            Instantiate(ruins, transform.position, transform.rotation);
            ruins.transform.parent = null;
        }

        //gameObject.SetActive(false);
        Destroy(gameObject);

    }
}
